package com.example.tool.conf;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.tool.bean.business.wdt.SelfOrderDO;
import com.example.tool.service.selforder.SelfOrderService;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryTrack;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil.YTO;
import static com.example.tool.util.ExpressDeliveryUtil.TrackTypeEnum.SIGNED;

@Component
public class YtoScheduledTasks {
    @Autowired
    private SelfOrderService selfOrderService;

    //     @Scheduled(cron = "0 0 * * * *", zone = "Asia/Shanghai")
    public void scheduledTasks() {
        List<SelfOrderDO> list = selfOrderService.list(new QueryWrapper<SelfOrderDO>().eq("logistics_type", YTO).eq("if_signed", false).isNotNull("logistics_no"));
        for (SelfOrderDO order : list) {
            String logisticsNo = order.getLogisticsNo();
            if (StringUtils.isNotBlank(logisticsNo)) {
                ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(logisticsNo);
                Boolean succeed = result.getSucceed();
                if (succeed) {
                    List<ExpressDeliveryTrack> tracks = result.getTracks();
                    if (!tracks.isEmpty()) {
                        ExpressDeliveryTrack edTrack = tracks.get(tracks.size() - 1);
                        String scanType = edTrack.getScanType();
                        String latestProgress = order.getLatestProgress();
                        if (!ObjectUtil.equal(scanType, latestProgress)) {
                            order.setLatestProgress(scanType);
                            if (ObjectUtil.equal(scanType, SIGNED.getCode())) {
                                order.setSignFlag(true);
                            }
                            selfOrderService.updateById(order);
                            WarehouseMsgConfig.logisticsMonitoring(result);
                        }


                    }


                }


            }
        }

    }

}
